package cn.hr.service.impl;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.annotation.Resource;

import cn.hr.dao.mapper.MissionTypeMapper;
import cn.hr.pojo.MissionType;
import cn.hr.utils.Constants;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import cn.hr.dao.mapper.ArchivesMapper;
import cn.hr.pojo.Archives;
import cn.hr.service.ArchivesService;

/**
 * 人事档案服务接口实现类
 *
 * @author MO
 */
@CacheConfig(cacheNames = "archives")
@Scope("prototype")
@Service("archivesService")
public class ArchivesServiceImpl implements ArchivesService {
    @Resource
    private ArchivesMapper archivesMapper;

    @Resource
    private MissionTypeMapper missionTypeMapper;

    @Resource
    private SolrClient solrClient;

    @Override
    public boolean insert(Archives t) throws Exception {
        boolean flag = false;
        Integer id = archivesMapper.findMaxId() + 1;
        t.setCode("ARCHIVES_" + id);
        Map m=new HashMap();
        m.put("postId",t.getPostId());
        List<Map> list=archivesMapper.findListByCondition(m);
        System.out.println(list.get(0).get("fullName"));
        if (archivesMapper.insert(t) > 0) {
            SolrInputDocument doc = new SolrInputDocument();
            doc.setField("id", t.getId());
            doc.setField("code", t.getCode());
            doc.setField("createdDate", t.getCreatedDate());
            doc.setField("gender", t.getGender());
            doc.setField("auditStatus", t.getAuditStatus());
            doc.setField("postId", t.getPostId());
            doc.setField("status", t.getStatus());
            doc.setField("pName", list.get(0).get("pName"));
            doc.setField("fullName", list.get(0).get("fullName"));
            doc.setField("auditStatusString", list.get(0).get("auditStatus"));
            doc.setField("statusString", list.get(0).get("status"));
            solrClient.add(doc);
            solrClient.commit();
            MissionType missionType = new MissionType();
            missionType.setTypeId(12);
            missionType.setTableId(id);
            missionType.setCreatedDate(new Date());
            missionType.setCreatedById(t.getCreatedById());
            missionType.setName(t.getCode() + "人事檔案審核");
            missionTypeMapper.insert(missionType);
            flag = true;
        }
        return flag;
    }

    @Override
    public boolean update(Archives t) throws Exception {
        boolean flag = false;
        Map m=new HashMap();
        m.put("id",t.getId());
        List<Map> list= null;
        if (archivesMapper.update(t) > 0) {
            list = archivesMapper.findListByCondition(m);
            SolrInputDocument doc = new SolrInputDocument();
            doc.setField("id", t.getId());
            doc.setField("code", list.get(0).get("code"));
            doc.setField("name", list.get(0).get("name"));
            doc.setField("createdDate", list.get(0).get("createdDate"));
            doc.setField("gender", list.get(0).get("gender"));
            doc.setField("auditStatus", list.get(0).get("auditStatus"));
            doc.setField("postId", list.get(0).get("postId"));
            doc.setField("status", list.get(0).get("status"));
            doc.setField("pName", list.get(0).get("pName"));
            doc.setField("fullName", list.get(0).get("fullName"));
            doc.setField("auditStatusString", list.get(0).get("auditStatusString"));
            doc.setField("statusString", list.get(0).get("statusString"));
            solrClient.add(doc);
            solrClient.commit();
            flag = true;
        }
        return flag;
    }

    @Override
    public boolean delete(Integer id) throws Exception {
        boolean flag = false;
        if (archivesMapper.delete(id) == 1) {
            solrClient.deleteById(String.valueOf(id));
            solrClient.commit();
            flag = true;
        }
        return flag;
    }

    @Override
    public Archives get(Integer id) throws Exception {
        return archivesMapper.get(id);
    }

    @Override
    public PageInfo<Map> findListByCondition(Map m, int pageNo) throws Exception {
        StringBuilder sb = new StringBuilder();
        if (m.get("condition") != null && !m.get("condition").equals("")) {
            sb.append("code:*");
            sb.append(m.get("condition"));

            sb.append("* or name:*");
            sb.append(m.get("condition"));
            sb.append("*");

            if (m.get("status")!= null&&!m.get("status").toString().equals("0")){
                sb.append(" and status:");
                sb.append(m.get("status"));
            }
            if (m.get("auditStatus")!= null&&!m.get("auditStatus").toString().equals("0")){
                sb.append(" and auditStatus:");
                sb.append(m.get("auditStatus"));
            }
            if (m.get("pName")!= null&& !m.get("pName").equals("")){
                sb.append(" and pName:");
                sb.append(m.get("condition"));
            }
            if (m.get("fullName")!= null&&!m.get("fullName").equals("")){
                sb.append(" and fullName:");
                sb.append(m.get("condition"));
            }
            if (m.get("startDateQuery")!= null&&!m.get("startDateQuery").equals("")){
                sb.append(" and createdDate:[");
                sb.append(m.get("startDateQuery"));
                sb.append("T00:00:00Z TO ");
                if (m.get("finishDateQuery")!= null&&!m.get("finishDateQuery").equals("")){
                    sb.append(m.get("finishDateQuery"));
                    sb.append("T59:59:59.999Z ]");
                }else{
                    sb.append(" *]");
                }
            }

        } else {
            sb.append("*:*");
        }
        SolrQuery query = new SolrQuery();
        query.setQuery(sb.toString());

        query.setStart((pageNo - 1) * Constants.PAGESIZE);
        query.setRows(Constants.PAGESIZE);
        QueryResponse rsp = solrClient.query(query);
        SolrDocumentList list = rsp.getResults();
        List<Map> maps = new ArrayList<>();
        Map map = null;
        for (SolrDocument solr : list) {
            map = new HashMap();
            map.put("id", Integer.parseInt((String) solr.get("id")));
            map.put("code", solr.get("code"));
            map.put("name", solr.get("name"));
            map.put("pName", solr.get("pName"));
            map.put("fullName", solr.get("fullName"));
            map.put("status", solr.get("statusString"));
            map.put("gender", solr.get("gender"));
            map.put("auditStatus", solr.get("auditStatusString"));

            Date date=new Date(solr.get("createdDate").toString());
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            System.out.println(sdf.format(date));

            map.put("createdDate", sdf.format(date));
            maps.add(map);
        }
        PageInfo<Map> pageInfo = new PageInfo<>(maps);
        pageInfo.setTotal(list.getNumFound());
        pageInfo.setPages((int) ((list.getNumFound() - 1) / Constants.PAGESIZE + 1));
        pageInfo.setSize(Constants.PAGESIZE);
        pageInfo.setPageNum(pageNo);
        pageInfo.setPageSize(Constants.PAGESIZE);
        return pageInfo;
    }

    @Override
    public Long findCountByCondition(Map m) throws Exception {
        return archivesMapper.findCountByCondition(m);
    }


    @Override
    public boolean recover(Archives t) {
        boolean flag=false;
        Map m=new HashMap();
        m.put("id",t.getId());
        List<Map> list= null;
        if (archivesMapper.recover(t) == 1){
            try {
            list = archivesMapper.findListByCondition(m);
            SolrInputDocument doc = new SolrInputDocument();
            doc.setField("id", t.getId());
            doc.setField("code", list.get(0).get("code"));
            doc.setField("name", list.get(0).get("name"));
            doc.setField("createdDate", list.get(0).get("createdDate"));
            doc.setField("gender", list.get(0).get("gender"));
            doc.setField("auditStatus", list.get(0).get("auditStatus"));
            doc.setField("postId", list.get(0).get("postId"));
            doc.setField("status", list.get(0).get("status"));
            doc.setField("pName", list.get(0).get("pName"));
            doc.setField("fullName", list.get(0).get("fullName"));
            doc.setField("auditStatusString", list.get(0).get("auditStatusString"));
            doc.setField("statusString", list.get(0).get("statusString"));
                solrClient.add(doc);
                solrClient.commit();
            } catch (Exception e) {
                e.printStackTrace();
            }
            flag = true;
        }
        return flag;
    }

    @Override
    public boolean delFile(Integer id, Integer distinguish) throws SQLException {
        boolean flag = false;
        Archives archives = archivesMapper.selectPath(id, distinguish);
        if (distinguish == 0) {
            File file = new File(archives.getPicturePath());
            if (file.exists()) {
                file.delete();
            }
        }
        if (distinguish == 1) {
            File file = new File(archives.getResumePath());
            if (file.exists()) {
                file.delete();
            }
        }
        return archivesMapper.delFile(id, distinguish) > 0;
    }

    @Override
    public Archives selectPath(Integer id, Integer distinguish) throws SQLException {
        return archivesMapper.selectPath(id, distinguish);
    }

}
